var express = require('express');
var router = express.Router();

var sql = require('../sql/index');
var pro = require('../sql/col/Pro');

var xlsx = require('node-xlsx');
var uuid = require('node-uuid');

router.get('/', function(req,res, next) {
    res.send('产品相关接口')
});

/**
 * @api {get} /api/pro/list 获取商品列表数据
 * @apiName getApiProList
 * @apiGroup pro
 * 
 * @apiParam { Number } count 页码，默认值为1
 * @apiParam { Number } limitnum 每页显示的个数，默认值为10
 * 
 * 
 * @apiSuccessExample {json} Success-Response:
 *  res.send({
        code: 200,
        message: '获取商品的列表数据',
        data
    })
 * @apiSampleRequest /api/pro/list
 * @apiVersion 0.0.0 
 */
router.get('/list', (req,res,next) => {
    let { count, limitnum } = req.query;
    count = count * 1 || 1;
    limitnum = limitnum * 1 || 10;
    sql.paging(pro,{}, {_id:0},limitnum,count).then(data=> {
        res.send({
            code:200,
            message:'获取列表成功',
            data
        })
    });
});


/**
 * @api {get} /api/pro/detail 获取详情的数据
 * @apiName GetApiProDetail
 * @apiGroup pro
 * 
 * @apiParam { String } proid 产品的唯一值
 * 
 * @apiSuccessExample {json} Success-Response:
 *  res.send({
      code: 200,
      message: '获取详情的数据',
      data
    })
 * @apiSampleRequest /api/pro/detail
 * @apiVersion 0.0.0
 */
router.get('/detail', (req,res,next) => {
    const { proid } = req.query;
    sql.find(pro,{ proid } , {_id:0}).then(data => {
        res.send({
            code:200,
            message: '获取详情的数据',
            data
        })
    })  
})

router.get('/upload', (req,res,next) => {
    const file = __dirname + '/pro.xlsx';
    const data = xlsx.parse(file)[0].data;
    const arr = [];

    data.forEach((item,index)=> {
        if(index > 0) {
            arr.push({
                proid: 'pro_' + uuid.v4(), // 生成唯一值
                proname: item[1],
                category: item[2],
                brand: item[3],
                logo: item[4],
                proimg: item[5],
                price: item[6] * 1,
                desc: item[7],
                stock: item[8] * 1,
                sales: item[9] * 1,
                discount: item[10] * 1,
                rating: item[11] * 1
            })
        }
    });

    //sql.delete(pro,{},1).then(()=> {
        sql.insert(pro,arr).then(()=> {
            res.send({
                code:200,
                message: '上传商品成功'
            })
        })
      //  res.send({
      //      code:200,
      //      message:'删除成功'
      // })
    //})

   
    
    // res.send(data);
})

module.exports = router;

